package com.yuandian.management.utils;//package com.yuandian.admin.modules.probe.helper.utils;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 迁移bpm3.0
 */
public class XmlUtils {
	private static String DEFAULT_ROOT_NAME="root";
	/**
	 * 根据map 得到Document对象  map中根元素key 为root
	 * @return
	 */
	public static  Document getEmptyDocument(String rootName) {
		Document document = DocumentHelper.createDocument();
		if(rootName==null || "".equals(rootName.trim())){
			rootName=DEFAULT_ROOT_NAME;
		}
		@SuppressWarnings("unused")
		Element rootElement=document.addElement("rootName");
		return document;
	}
	/**
	 * 创建子节点
	 * @param parentElement   父节点
	 * @param elementName     子节点名
	 * @param elementTextValue  子节点文本值  没有置""
	 * @return 返回创建的子节点
	 */
	public static Element createSubElement(Element parentElement,String elementName,String elementTextValue){
		Element subElement=parentElement.addElement(elementName);
		if(!"".equals(elementTextValue)){
			subElement.setText(elementTextValue);
		}
		return subElement;
	}
	/**
	 * 创建节点属性
	 * @param element         要添加属性 的节点
	 * @param attributeName   属性名
	 * @param attributeValue  属性值
	 * @return
	 */
	public static Element createAttribute(Element element,String attributeName,String attributeValue){
		element.addAttribute(attributeName, attributeValue);
		return element;
	}
	/**
	 * 将Document对象写入文件
	 * @param file
	 * @param document
	 * @throws IOException
	 */
	public static void writeDocument(File file,Document document) throws IOException{
		FileOutputStream fos=new FileOutputStream(file);
		BufferedOutputStream bos=new BufferedOutputStream(fos);
		writerDocument(bos, document);
		bos.close();
		fos.close();
	}
	/**
	 * 将document对象写入流中
	 * @param bos
	 * @param document
	 * @throws IOException
	 */
	public static void writerDocument(BufferedOutputStream bos ,Document document) throws IOException{
		//格式化
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter writer=new XMLWriter(bos,format);
//		format.setEncoding("GBK");
		writer.write(document);
		writer.flush();
		writer.close();
	}

	public static void main(String[] args) {
		try {
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd@HHmmssSSS");
			Date now=new Date();
			String rootPath="L:\\test";
			File file=new File(rootPath+File.separator+sdf.format(now)+".xml");
			Document doc=getEmptyDocument("");


			writeDocument(file, doc);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
